import { ITodoData } from "./js/typing"
import TodoEvent from "./TodoEvent"

((doc) => {
    const saveBtnDom: HTMLButtonElement = document.querySelector('#saveBtn')!
    const todoWrapper: HTMLElement = document.querySelector('#todo-wrapper')!
    const inputDom: HTMLInputElement = document.querySelector('#inputArea')!

    let todoData: ITodoData[] = []
    let todoEvent: TodoEvent

    const init = () => {
        todoEvent = new TodoEvent(todoData, todoWrapper, inputDom)
        bindEvent()
    }

    const bindEvent = () => {
        saveBtnDom.addEventListener('click', handleAdd, false)
        todoWrapper.addEventListener('click', handleListerClick, false)
    }

    const handleAdd = () => {
        const id = new Date().getTime()
        const inpVal = (document.querySelector('#inputArea') as HTMLInputElement).value
        const todoItem: ITodoData = {
            id,
            content: inpVal,
            complete: false
        }
        todoEvent.addTodoEvent(todoItem)
    }

    const handleListerClick = (e: MouseEvent) => {
        const tagName = (e.target as HTMLElement).tagName
        let id: number = parseInt((e.target as HTMLElement).dataset.id!)
        switch (tagName) {
            case 'INPUT':
                todoEvent.changeComplete(id)
                break;
            case 'BUTTON':
                todoEvent.removeTodoEvent(id)
                break;
        }
    }

    init()
})(document)